package cn.itcast.n4.reentrant;

import java.util.concurrent.locks.ReentrantLock;

/**
 * className: TestFair
 * description:
 * date: 2023/3/8 0008-14:54
 * <p>
 * project: concurrent
 * package: cn.itcast.n4.reentrant
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class TestFair {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock(false);

        lock.lock();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "t" + i).start();
        }

        // 1s 之后去争抢锁
        Thread.sleep(1000);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }

            }, "强行插入").start();
        }
        lock.unlock();
    }
}
